package cn.tedu.web.controller;

import cn.tedu.web.service.IOrderService;
import cn.tedu.web.utils.Constant;
import cn.tedu.web.mapper.OrderMapper;
import cn.tedu.web.entity.Order;
import cn.tedu.web.entity.StorageOrder;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 【订单表】 前端控制器
 * </p>
 * order
 * 
 * @author issen
 * @since 2021-10-18
 */
@SuppressWarnings("all")
@RestController
@RequestMapping("/api/order")
public class OrderController {

    @Autowired
    public IOrderService orderService;
    @Autowired
    public OrderMapper orderMapper;

    @ApiOperation(value = "新增")
    /**
     * 将订单信息临时存储到会话中
     */
    @PostMapping("storage")
    public String storage(@RequestBody StorageOrder StorageOrder, HttpSession session) throws IOException {
        session.setAttribute(Constant.STORAGE_KEY, StorageOrder);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // System.out.println(session.getAttribute(Constant.STORAGE_KEY));
        StorageOrder storage = StorageOrder;
        Integer uid = storage.getAddress().getUid();
        // 筛选条件(uid,时间间隔,总价,地址)
        QueryWrapper queryWrapper = new QueryWrapper<Order>();
        queryWrapper.eq("uid", uid);
        queryWrapper.eq("total_amount", storage.getTotalAmount());
        queryWrapper.eq("address", storage.getAddress().combine());
        System.out.println(storage.getAddress().combine());
        Date now = new Date();
        Date now_10 = new Date(now.getTime() - 10 * 1000);
        queryWrapper.between("create_time", formatter.format(now_10), formatter.format(now));
        if (orderService.getOne(queryWrapper) == null) {
            Order order = orderService.create(storage, uid);
            if (order != null && order.getId() != null) {
                System.out.println("创建订单成功！");
                // 清空临时订单
                session.setAttribute(Constant.STORAGE_KEY, null);
                return "/payment?o=" + order.getOrderId();
            } else {
                return "error-创建订单失败";
            }
        }
        return "confirm-/payment?o=" + orderService.getOne(queryWrapper).getOrderId();

    }

    /**
     * 从会话中获取临时存储的订单信息
     */
    @ResponseBody
    @GetMapping("storage")
    public StorageOrder storage(HttpSession session) throws IOException {
        StorageOrder order = (StorageOrder) session.getAttribute(Constant.STORAGE_KEY);
        System.out.println(order);
        return order;
    }

    /**
     * 通过临时存储的订单信息来创建新订单 点击立即支付---判断是否登录(前端路由守卫)
     * ----未登录---跳转到登录页---登录---返回结算页---从后台取到临时订单,添加uid ----已登录(有uid)
     * (在支付页挂载时)保存订单信息---进入支付页
     */
    @GetMapping("create")
    public String create(HttpSession session) {
        StorageOrder storage = (StorageOrder) session.getAttribute(Constant.STORAGE_KEY);
        // 从 session 中获取当前登录的用户的ID
        // Integer uid = (Integer) session.getAttribute(Constant.SESSION_KEY);
        Integer uid = storage.getAddress().getUid();
        System.out.println(uid);
        // 创建之前对订单进行判断,1.时间差小于1min 2.物品和物品数相等
        // 满足以上条件先不创建订单,返回查询到达订单order_id并向前端请求确认信息
        System.out.println("正在创建订单...");
        Order order = orderService.create(storage, uid);
        if (order != null && order.getId() != null) {
            System.out.println("创建订单成功！");
            // 清空临时订单
            session.setAttribute(Constant.STORAGE_KEY, null);
            return "/payment?o=" + order.getOrderId();
            // return "/payment";
        }
        return null;
    }

    @ResponseBody
    @GetMapping("get/{orderId}")
    public Order getOrder(@PathVariable("orderId") String orderId) throws IOException {
        QueryWrapper queryWrapper = new QueryWrapper<Order>();
        queryWrapper.eq("order_id", orderId);
        return orderMapper.selectOne(queryWrapper);
    }

    @ResponseBody
    @GetMapping("/list")
    public List<Order> listOrder() {
        QueryWrapper queryWrapper = new QueryWrapper<Order>();
        // queryWrapper.eq("uid", uid);
        return orderMapper.selectList(queryWrapper);
    }
    
    @ApiOperation(value = "改变状态")
    @PostMapping("/changeStatus")
    public ResponseEntity<Object> changeStatus(@RequestBody Order order, HttpServletRequest request) {
        UpdateWrapper updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("status", order.getStatus());
        updateWrapper.eq("id", order.getId());
        orderService.update(updateWrapper);
        return new ResponseEntity<>("修改完成", HttpStatus.OK);
    }

}
